package com.hao.thread;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

public class ThreadBigdecimalBugTest {
    private static final SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        ExecutorService service = new ThreadPoolExecutor(3, 3, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        /**
         * 线程1
         * BigDecimal的divide设置正确的精度
         * */
        service.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "---" + sfd.format(new Date()));
            int i = 0;
            while (i < 1000000) {
                new BigDecimal(1).divide(new BigDecimal("3"), 2, BigDecimal.ROUND_HALF_DOWN);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
            System.out.println(Thread.currentThread().getName() + "---" + sfd.format(new Date()));
        });

        /**
         * 线程2
         *
         * */
        service.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "---" + sfd.format(new Date()));
            int i = 0;
            while (i < 1000000) {
                new BigDecimal(1).divide(new BigDecimal("3")).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
            System.out.println(Thread.currentThread().getName() + "---" + sfd.format(new Date()));
        });

        /**
         * 线程3
         *
         * */
        service.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "---" + sfd.format(new Date()));
            int i = 0;
            while (i < 1000000) {
                // 除不设置精度，遇到无限循环导致线程 wait 陷入全部等待。
                new BigDecimal(1).divide(new BigDecimal("3")).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
            System.out.println(Thread.currentThread().getName() + "---" + sfd.format(new Date()));
        });
    }
}
